package com.zut.blocks.web.filter;

import com.zut.blocks.base.common.Login;
import com.zut.blocks.base.util.UserUtil;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lxd
 * @date 2020/12/28 10:30
 */
@Component
@WebFilter(filterName = "userFilter", urlPatterns = "/*")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        fillUserInfo((HttpServletRequest) request);

        chain.doFilter(request, response);

        clearAllUserInfo();
    }

    private void clearAllUserInfo() {
        UserUtil.clearAllUserInfo();
    }

    private void fillUserInfo(HttpServletRequest request) {
        // 用户信息
        Login user = getUserFromSession(request);

        if (user != null) {
            UserUtil.setUser(user);
        }
    }

    private Login getUserFromSession(HttpServletRequest request) {
        //TODO 如果不参加session，model.addAttribute(UserUtil.KEY_USER, username);报错
        HttpSession session = request.getSession(true);

        if (session == null) {
            return null;
        }

        // 从session中获取用户信息放到工具类中
        return (Login) session.getAttribute(UserUtil.KEY_USER);
    }

    @Override
    public void destroy() {

    }
}
